
<template>
  <a-modal
    class="approver"
    title="选择审批人"
    :width="1200"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :maskClosable="false"
    @cancel="deleteApproval(true)"
    :closable="disabledBtn?false:true"
  >
    <!-- 流程图 -->
    <a-spin :spinning="flowChartLoading">
      <img
        class="flow-chart"
        :src="flowChart"
      />

      <!-- 流程图 -->
      <!-- 流程节点列表 -->
      <a-table
        ref="table"
        bordered
        row-key="key"
        :columns="columns"
        :data-source="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :show-pagination="false"
        :loading="flowChartLoading"
      >
        <template
          slot="userName"
          slot-scope="text, record"
        >
          <Ellipsis
            v-if="record.completed === 1"
            :length="50"
            tooltip
            placement="right"
          >
            {{ text }}
          </Ellipsis>
          <a-select
            v-else
            v-model="record.userId"
            mode="multiple"
            class="width-100"
            placeholder="请选择处理人"
            showArrow
          >
            <a-select-option
              v-for="{ userId, name } in record.userList"
              :key="userId"
            >
              {{ name }}
            </a-select-option>
          </a-select>
        </template>
        <template
          slot="opinions"
          slot-scope="text"
        >
          <Ellipsis
            :length="30"
            tooltip
          >
            {{ text }}
          </Ellipsis>
        </template>
      </a-table>
    </a-spin>
    <!-- 流程节点列表 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="rules"
      v-if="isUrgent"
    >
      <a-form-model-item
        label="是否加急"
        prop="urgent"
      >
        <a-select v-model="form.urgent">
          <a-select-option value="2"> 是 </a-select-option>
          <a-select-option value="1"> 否 </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    <template slot="footer">
      <a-button
        @click="deleteApproval"
        :disabled="disabledBtn"
      > 取消 </a-button>
      <a-button
        type="primary"
        @click="handleOk"
        :disabled="disabledBtn"
      > 提交 </a-button>
    </template>
  </a-modal>
</template>
<script>
import { getFlowChart } from '@/api/process'
import { columns } from './model'
import { Ellipsis } from '@/components'
import { getCurrentProcessList } from '@/utils/requestWithParams.js'
import { updateVariables, deleteProcessByBusinessId } from '@/api/indexPage'
export default {
  name: 'SetApprover',
  components: {
    Ellipsis
  },
  props: {
    // 模态框显示隐藏
    visible: {
      type: Boolean,
      default: false
    },
    //是否加急
    isUrgent: {
      type: Boolean,
      default: false
    },
    businessId: {
      type: [String, Number],
      default: ''
    },
    //是否关闭上级页面
    isCloseUpper: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 流程图
      flowChart: '',
      // 流程图加载
      flowChartLoading: true,
      // 提交loading
      confirmLoading: false,
      // 表头
      columns,
      form: {
        urgent: '1'
      },
      rules: {
        urgent: [{ required: true, message: '请选择是否加急', trigger: 'blur' }]
      },
      loadData: [],
      timer: null,
      //禁用按钮
      disabledBtn: true,
      loadingTab: false,
      tenSecond: 5 //10秒之后清除定时器。因为有可能没数据
    }
  },
  watch: {
    // 监听模态框显示隐藏
    visible: {
      handler(val) {
        if (val) {
          this.flowChartLoading = true
          let that = this
          clearInterval(this.timer)
          this.timer = null
          this.timer = setInterval(() => {
            that.businessId && that.getAll()
            that.tenSecond--
          }, 2000)
        } else {
          this.flowChartLoading = false
          this.flowChart = ''
        }
      }
    }
  },
  mounted() {
    // this.loadingTab = true
    // this.flowChartLoading = true
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  methods: {
    //获取所有的数据
    async getAll() {
      this.loadingTab = true
      this.flowChartLoading = true
      await this.getFlowChart()
      await this.getLoadData()
      this.loadingTab = false
      this.flowChartLoading = false
    },
    getFlowChart() {
      getFlowChart(this.businessId)
        .then((res) => {
          if (res.code === this.SUCCESS_CODE) {
            this.flowChart = 'data:image/png;base64,' + res.data
          }
        })
        .finally(() => {})
    },
    async getLoadData() {
      let data = await getCurrentProcessList.call(this, { businessId: this.businessId, newApi: true })
      //请求成功，清除定时器
      if (data?.status === 200 || this.tenSecond < 0) {
        this.loadData = data?.data
        //有数据才放开按钮
        if (this.loadData) {
          this.disabledBtn = false
        }
        clearInterval(this.timer)
        this.timer = null
        return
      } else if (data?.status === 500 || data?.code === 500) {
        //接口报错清除
        clearInterval(this.timer)
        this.timer = null
      }
    },

    /**
     * @description: 确认
     * @return {void}
     */
    handleOk() {
      let req = {
          variables: {}
        },
        obj = {}
      req.businessId = this.businessId
      if (this.loadData.length) {
        this.loadData.map((item) => {
          //userId 为空就不传
          if (item.taskDefKey && item.userId?.length) {
            obj[item.taskDefKey] = {
              assgins: item.userId.join(','),
              assignTypeEnum: '2'
            }
          }
        })
      }
      req.variables = obj
      if (this.isUrgent) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            req.urge = this.form.urgent * 1 === 2 ? true : false
            this.submit(req)
          } else {
            this.$message.warning('请填写完所有必填项信息')
          }
        })
      } else {
        this.submit(req)
      }
    },
    submit(str) {
      this.flowChartLoading = true
      updateVariables(str).then((res) => {
        this.flowChartLoading = false
        if (res.status == 200) {
          // 追加自定义事件 不改原有逻辑 可以不受限制 想怎么处理 就怎么处理
          this.$emit('closeDialog')
          this.$message.success('选择审批人成功！')
          if (this.isCloseUpper) {
            this.$multiTab.close()
            this.$emit('closevisible')
          } else {
            this.$emit('closevisible')
            this.$emit('close',true) // 会触发爷组件的submit事件
          }
        }
      })
    },
    /**
     * @description: 关闭
     * @return {void}
     */
    handleCancel() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      if (this.isCloseUpper) {
        this.$multiTab.close()
      } else {
        this.$emit('closevisible')
        this.$emit('close') // 会触发爷组件的submit事件
      }
    },
    /**
     * @description: 取消审批
     * @return {void}
     */
    deleteApproval(flag) {
      let that = this
      //有数据才能取消
      if (this.loadData && this.loadData?.length) {
        this.$confirm({
          title: '温馨提示',
          content: '确定要取消审批？',
          onOk: () => {
            that.flowChartLoading = true
            that.disabledBtn = true
            deleteProcessByBusinessId(this.businessId).then((res) => {
              that.flowChartLoading = false
              that.disabledBtn = false
              if (res.status === 200) {
                // 追加自定义事件 不改原有逻辑 可以不受限制 想怎么处理 就怎么处理
                this.$emit('closeDialog')
                this.$message.success('取消成功！')
                if (that.isCloseUpper) {
                  that.$emit('closevisible')
                  that.$multiTab.close()
                } else {
                  that.$emit('close',false)// 会触发爷组件的submit事件
                  that.$emit('closevisible')
                }
              } else {
                that.$multiTab.close()
              }
            })
          },
          onCancel() {
            that.$emit('close',false) // 会触发爷组件的submit事件
          }
        })
      } else {
        this.$confirm({
          title: '温馨提示',
          content: '确定要取消审批？',
          onOk: () => {
            if (this.isCloseUpper) {
              this.$multiTab.close()
              this.$emit('closevisible')
            } else {
              that.$emit('close',false) // 会触发爷组件的submit事件
              this.$emit('closevisible')
            }
          }
        })
      }
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.flow-chart {
  width: 100%;
  margin-bottom: 20px;
}
.approver {
  @{deep} .ant-form {
    margin-top: 20px;
    .ant-col-6 {
      width: 100px;
    }
  }
  @{deep} .ant-form-item .ant-form-item-control-wrapper {
    width: 300px;
  }
  @{deep}.ant-form-item-children{
    .ant-select-selection{
      border: 1px solid #e4ac0b;
      background-color: #fff9e8;
    }
  }
}
</style>
